/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Apr 14, 2012
 * Time: 4:14:41 PM
 * To change this template use File | Settings | File Templates.
 */
/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Mar 31, 2012
 * Time: 8:29:44 PM
 * To change this template use File | Settings | File Templates.
 */
/***************************/

  //global vars
	var form = $("#frmData");
	var assignPrivilege = $("#assignRole");

$(document).ready(function(){   

    disableForm("frmData");
} );

//////////// data Grid /////////
var mygrid;
var timeoutHnd;
var flAuto = false;
function gridGenerator() {
    mygrid = new dhtmlXGridObject('gridbox');
    mygrid.setImagePath("images/dhtmlx/imgs/");
    mygrid.setHeader("User Name,Name,NIC,Email,Profile Id,status");
    mygrid.setInitWidths("150,350,200,300,200,10");
    mygrid.setColAlign("left,left,left,left,left,left");
    mygrid.setColSorting("server,server,server,na,na,na");
    mygrid.setColTypes("ro,ro,ro,ro,ro,ro");
    if (mygrid.setColspan){
       mygrid.attachEvent("onBeforeSorting", customColumnSort);
    }   

    //mygrid.enablePaging(mode,pageSize,pagesInGrp,pagingControlsContainer,showRecInfo,pagingStateContainer);
    mygrid.enablePaging(true,10, 10, "pagingArea", true, "infoArea");
   // mygrid.setPagingSkin("bricks");
    mygrid.setPagingSkin("toolbar", "dhx_skyblue");
    //mygrid.setStyle("background-color:navy;color:white; font-weight:bold;", "","color:red;", "");
    mygrid.init();
    mygrid.setSkin("xp"); //other skins (sbdark,gray,mt,xp,clear,modern,light,dhx_skyblue )
    mygrid.attachEvent("onBeforePageChanged", function() {
        if (!this.getRowsNum()){
            return false;
        }
        return true;
    });
    mygrid.sortField_old = mygrid.sortField;
    mygrid.sortField = function() {
         mygrid.setColSorting("str,str,str,str,str,str");
        if (customColumnSort(arguments[0]))
        mygrid.sortField_old.apply(this, arguments);
    }
    mygrid.setColumnHidden(4,true);
    mygrid.setColumnHidden(5,true);
    mygrid.sortRows = function(col, type, order) {}
    mygrid.attachEvent("onRowSelect",doOnRowSelected);
    mygrid.attachEvent("onXLE", showLoading);
    mygrid.attachEvent("onXLS", function() {
        showLoading(true)
    });    
    mygrid.loadXML("?user/gridUser&un=" + Date.parse(new Date()),function(){
      var myToolbar=mygrid.aToolBar;
        //myToolbar.setSkin("dhx_black");
        
   });
}

function showLoading(fl) {
    var span = document.getElementById("recfound");
    if (!span)
        return;
    if (!mygrid._serialise) {
        span.innerHTML = "<i>Loading... available in Professional Edition of dhtmlxGrid</i>";
        return;
    }
    span.style.color = "red";
    if (fl === true)
    span.innerHTML = "loading...";
    else
    span.innerHTML = "";
}

function doSearch(ev) {
    if (!flAuto)
    return;
    var elem = ev.target || ev.srcElement;
    if (timeoutHnd)
    clearTimeout(timeoutHnd);
    timeoutHnd = setTimeout(reloadGrid, 500);
}
function reloadGrid() {
    var searchCriteriaUserName = document.getElementById("searchCriteria.userName").value;
    var searchCriteriaName = document.getElementById("searchCriteria.name").value;
    showLoading(true);
    mygrid.clearAndLoad("?user/gridUser&userName=" + searchCriteriaUserName + "&name=" + searchCriteriaName + "&orderBy=" + window.s_col + "&direction=" + window.a_direction);
    if (window.a_direction)
    mygrid.setSortImgState(true, window.s_col, window.a_direction);
}
function enableAutosubmit(state) {
    flAuto = state;
    document.getElementById("submitButton").disabled = state;
}

function customColumnSort(ind) {
    if (ind == 4) {
        alert("Table can't be sorted by this column.");
        if (window.s_col)
        mygrid.setSortImgState(true, window.s_col, window.a_direction);
        return false;
    }
    var a_state = mygrid.getSortingState();
    window.s_col = ind;
    window.a_direction = ((a_state[1] == "des") ? "asc": "des");
   reloadGrid();
    return true;
}

function doOnRowSelected(rowID,celInd){
    clearForm("frmData");
    disableForm("frmData");
    document.getElementById("id").value  = rowID;
    getUserRole(rowID) ;
    handleDefaultButtons("gridclick");
    enableElement("btnChangPass");
}

function initialize(fnAfterInit) {
    clearForm("frmData");
    disableForm("frmData");
    disableElement("btnSave");
    disableElement("btnEdit");

}
function edit(){
    enableForm("frmData");
    enableElement("btnSave");
    enableElement("btnChangPass");
}
function selectAllOption(id){
   $(id).find('option').each(function() {
	            $(this).attr('selected', 'selected');
	        });
}
function moveOptionRight(){
     $('#avbRole option:selected').each( function() {
                $('#assignRole').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
            $(this).remove();
        });
}
function moveOptionLeft(){
     $('#assignRole option:selected').each( function() {
            $('#avbRole').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
            $(this).remove();
        });
}
function moveAllOptionRight(){
       selectAllOption('#avbRole');
       moveOptionRight();
}
function moveAllOptionLeft(){
       selectAllOption('#assignRole');
       moveOptionLeft();
}
function save(){
    selectAllOption('#assignRole');
        var params = serializeForm("frmData") ;
        ajaxPost("?user/userRole", params, function(data) {

			var response =JSON.parse(data);

			if (response.status==false) {


				return;
			} 
            $("#avbRole").find('option').remove().end();
            $("#assignRole").find('option').remove().end();
			// Success
			//actionResponse = response;
            $("#messagePanel").removeClass();
            $("#messagePanel").addClass(response.type);
            $("#messagePanel").html(response.message ) ;

           // $("#messagePanel").addClass("error");
           // $("#messagePanel").html(data) ;
            reloadGrid();
			initialize();

		});  
    handleDefaultButtons("save");  
}

function closePage(){
    window.location.href="?home";
}

function getUserRole(RoleId){
     var params = serializeForm("frmData") ;
        ajaxPost("?user/getUserRole", params, function(data) {

			var roleData =JSON.parse(data);
                $("#avbRole").find('option').remove().end();
                $("#assignRole").find('option').remove().end();
                for (key in roleData[0]) {
                        if (typeof (roleData[0][key] == 'string')) {
                            $("#avbRole").append('<option value="' + key + '">' + roleData[0][key] + '</option>');
                            }
                        }

                for (key in roleData[1]) {
                        if (typeof (roleData[1][key] == 'string')) {
                            $("#assignRole").append('<option value="' + key + '">' + roleData[1][key] + '</option>');
                            }
                        }
		});
}
function onLoad(){
     initialize();
     gridGenerator();
     enforcePrivileges();
}
onLoad();
